import { AUTH_KEY } from "@/constants"
const cookieparser = process.server ? require("cookieparser") : undefined

const shouldPrintIp = false

export const actions = {
  // 服务端渲染周期
  async nuxtServerInit({ commit }, { req }) {
    // 打印IP
    shouldPrintIp && printIp(req)

    // 登录保存
    let token = ""
    if (req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie) || {}
      token = parsed[AUTH_KEY]
    }
    commit("user/SET_USER", { token })
  }
}

function printIp(req) {
  const ip = (
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress
  ).split(",")[0]
  console.log(`用户访问：${ip}`)
}
